﻿using DevExpress.XtraCharts;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mMachine.Common
{
    public class ExportHelper
    {
        #region 导出


        /// <summary>
        /// 创建打印Componet
        /// </summary>
        /// <param name="printable"></param>
        /// <returns></returns>
        PrintableComponentLink CreatePrintableLink(IPrintable printable)
        {
            ChartControl chart = printable as ChartControl;
            if (chart != null)
                chart.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Stretch;
            PrintableComponentLink printableLink = new PrintableComponentLink() { Component = printable };
            return printableLink;
        }

        /// <summary>
        /// 导出Excel，支持多个控件同时导出在同一个Sheet表
        /// </summary>
        /// <param name="panels">控件集</param>
        public void ExportToExcel(params IPrintable[] panels)
        {
            string fileName = string.Empty;

            try
            {
                if (!Directory.Exists(@"D:\MESTemp"))
                    Directory.CreateDirectory(@"D:\MESTemp");
                SaveFileDialog fileDialog = new SaveFileDialog();
                fileDialog.Title = "图表Excel";
                fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
                DialogResult dlg = fileDialog.ShowDialog();
                //OpenFileDialog dlg = new OpenFileDialog();
                //dlg.FileName = "Chart_" + DateTime.Now.Date.ToString("yyyy-MM-dd");  // 默认文件名
                //dlg.Title = "Export Excel";
                //dlg.DefaultExt = "xlsx"; // 扩展名
                //dlg.Filter = "Excel file(*.xlsx)|*.xlsx|Excel file(*.xls)|*.xls";                 

                if (dlg == DialogResult.OK)
                {
                    fileName = fileDialog.FileName;
                    //this.gv.RowStyle -= gv_RowStyle; //去除选中行样式

                    PrintingSystem ps = new PrintingSystem();
                    CompositeLink link = new CompositeLink(ps);

                    ps.Links.Add(link);
                    foreach (IPrintable panel in panels)
                    {
                        link.Links.Add(CreatePrintableLink(panel));
                    }

                    link.Landscape = true;//横向           
                                          //判断是否有标题，有则设置         

                    link.CreateDocument(); //建立文档
                                           //ps.PreviewFormEx.Show();//进行预览  
                                           //ps.Print(); //打印
                    try
                    {
                        if (string.IsNullOrEmpty(fileName))
                        {
                            return;
                        }
                        int count = 1;
                        //在重复名称后加（序号）
                        while (File.Exists(fileName))
                        {
                            if (fileName.Contains(")."))
                            {
                                int start = fileName.LastIndexOf("(");
                                int end = fileName.LastIndexOf(").") - fileName.LastIndexOf("(") + 2;
                                fileName = fileName.Replace(fileName.Substring(start, end), string.Format("({0}).", count));
                            }
                            else
                            {
                                int find = fileName.LastIndexOf(".");
                                fileName = fileName.Insert(find, string.Format("({0})", count));
                            }
                            count++;
                        }

                        if (fileName.LastIndexOf(".xlsx") >= fileName.Length - 5)
                        {
                            XlsxExportOptions options = new XlsxExportOptions();
                            options.SheetName = "图表"; //修改sheet页命名
                            link.PrintingSystem.ExportToXlsx(fileName, options);
                        }
                        else
                        {
                            XlsExportOptions options = new XlsExportOptions();
                            options.SheetName = "图表"; //修改sheet页命名
                            link.PrintingSystem.ExportToXls(fileName, options);
                        }

                        if (DevExpress.XtraEditors.XtraMessageBox.Show("保存成功，是否打开文件？", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            System.Diagnostics.Process.Start(fileName);//打开指定路径下的文件
                        }
                    }
                    catch (Exception)
                    {
                        //提示...
                    }

                    // this.gv.RowStyle += gv_RowStyle;
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }

        }

        #endregion

        #region 打印
        public void PrintPreview(params IPrintable[] panels)
        {
            try
            {
                PrintingSystem ps = new PrintingSystem();
                CompositeLink link = new CompositeLink(ps);
                ps.Links.Add(link);
                foreach (IPrintable panel in panels)
                {
                    link.Links.Add(CreatePrintableLink(panel));
                }

                link.Landscape = true;//横向           
                                      //判断是否有标题，有则设置         

                link.CreateDocument(); //建立文档
                                       // ps.PreviewFormEx.Show();//预览  
                ps.PrintDlg();//打印选择打印机
                //ps.Print(); //直接打印                  

            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }
        #endregion
    }
}
